import json
from datetime import datetime
from hyperliquid.get_capital_rate import get_capital_rate_hyperliquid
from hyperliquid.get_order import get_order_hyperliquid
from okx.okx_websocket import start_okx_websocket
from dydx.dydx_websocket import start_dydx_websocket
from dydx.get_capital_rate_dydx import get_capital_rate_dydx
from okx.get_capital_rate_okx import get_funding_rate_okx
from binance_my.binance_websocket import start_binance_websocket
from binance_my.get_capital_rate import get_capital_rate_binance
import schedule
import time
import threading
from dotenv import load_dotenv
import os
import redis


pool_binance_fundingrate = redis.ConnectionPool(host='localhost', port=6379, db=2)
r_binance_fundingrate = redis.Redis(connection_pool=pool_binance_fundingrate)

pool_okx_fundingrate = redis.ConnectionPool(host='localhost', port=6379, db=4)
r_okx_fundingrate = redis.Redis(connection_pool=pool_okx_fundingrate)

pool_hyper_orderbook = redis.ConnectionPool(host='localhost', port=6379, db=5)
r_hyper_orderbook = redis.Redis(connection_pool=pool_hyper_orderbook)

pool_hyper_fundingrate = redis.ConnectionPool(host='localhost', port=6379, db=6)
r_hyper_fundingrate = redis.Redis(connection_pool=pool_hyper_fundingrate)

pool_dydx_fundingrate = redis.ConnectionPool(host='localhost', port=6379, db=8)
r_dydx_fundingrate = redis.Redis(connection_pool=pool_dydx_fundingrate)


load_dotenv()
okx_token_str = os.getenv('OKX_TOKEN')
if okx_token_str:
    okx_token_array = okx_token_str.split(',')
    okx_token_array = [item.strip() for item in okx_token_array]
else:
    print("环境变量 'OKX_TOKEN' 未设置")

binance_token_str = os.getenv('BINANCE_TOKEN')
if binance_token_str:
    binance_token_array = binance_token_str.split(',')
    binance_token_array = [item.strip() for item in binance_token_array]
else:
    print("环境变量 'BINANCE_TOKEN' 未设置")

hyperliquid_token_str=os.getenv('Hyperiquid_TOKEN')
if hyperliquid_token_str:
    hyperliquid_token_array = hyperliquid_token_str.split(',')
    hyperliquid_token_array = [item.strip() for item in hyperliquid_token_array]
else:
    print("环境变量 'Hyperiquid_TOKEN' 未设置")


dydx_token_str=os.getenv('DYDX_TOKEN')
if dydx_token_str:
    dydx_token_array = dydx_token_str.split(',')
    dydx_token_array = [item.strip() for item in dydx_token_array]
else:
    print("环境变量 'Hyperliquid_TOKEN' 未设置")

# host=os.getenv('host')
# user=os.getenv('user')

# password=os.getenv('password')
# if password==None:
#     print("数据库密码未设置")
#     password=""

def task_get_capital_rate_okx():
    global r_okx_fundingrate
    print("Executing Task get_capital_rate okx")
    alldata=get_funding_rate_okx(all_token=okx_token_array)
    current_time = datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    for data in alldata:
        try:
            r_okx_fundingrate.set(current_time+"-"+data["trading_pair"]+"-okx-fundingrate", json.dumps(data),ex=604800)
        except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutError) as e:
            print(f"Operation failed: {e}. Attempting to reconnect...")
            time.sleep(5)
            r_okx_fundingrate = redis.Redis(connection_pool=pool_okx_fundingrate)

def task_get_orderbook_hyperliquid():
    global r_hyper_orderbook
    print("Executing Task Hyperliquid")
    for token in hyperliquid_token_array:
        parts = token.rsplit('-', 1)
        trading_pair = parts[0]
        grouping = parts[1]
        json_data=get_order_hyperliquid(coin=trading_pair,nSigFigs=grouping)
        timestamp = datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
        try:
            trade_data = {
                "time": timestamp,
                "trading_pair": trading_pair,
                "buy_order": json_data["levels"][0],
                "sell_order": json_data["levels"][1]
            }
            r_hyper_orderbook.set(timestamp+"-"+trading_pair+"-hyper-orderbook", json.dumps(trade_data),ex=86400)
            time.sleep(0.3)
        except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutError) as e:
            print(f"Operation failed: {e}. Attempting to reconnect...")
            time.sleep(5)
            r_hyper_orderbook = redis.Redis(connection_pool=pool_hyper_orderbook)

def task_get_capital_rate_dydx():
    global r_dydx_fundingrate
    print("Executing Task get_capital_rate_dydx")
    data=get_capital_rate_dydx(all_token=dydx_token_array)
    timestamp = datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    try:
        for token_funding in data:
            r_dydx_fundingrate.set(timestamp+"-"+token_funding["trading_pair"]+"-dydx-funding", json.dumps(token_funding),ex=604800)
    except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutError) as e:
        print(f"Operation failed: {e}. Attempting to reconnect...")
        time.sleep(5)
        r_dydx_fundingrate = redis.Redis(connection_pool=pool_dydx_fundingrate)

def task_get_capital_rate_hyperliquid():
    global r_hyper_fundingrate
    print("Executing Task get_capital_rate hyperliquid")
    data = get_capital_rate_hyperliquid(token_array=hyperliquid_token_array)
    timestamp = datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    try:
        for token_funding in data:
            r_hyper_fundingrate.set(timestamp+"-"+token_funding["trading_pair"]+"-hyper-funding", json.dumps(token_funding),ex=604800)
    except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutError) as e:
        print(f"Operation failed: {e}. Attempting to reconnect...")
        time.sleep(5)
        r_hyper_fundingrate = redis.Redis(connection_pool=pool_hyper_fundingrate)

def task_get_capital_rate_binance():
    global r_binance_fundingrate
    print("Executing Task get_capital_rate binance")
    data = get_capital_rate_binance(token_array=binance_token_array)
    timestamp = datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    try:
        for token_funding in data:
            r_binance_fundingrate.set(timestamp+"-"+token_funding["trading_pair"]+"-binance-funding", json.dumps(token_funding),ex=604800)
    except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutError) as e:
        print(f"Operation failed: {e}. Attempting to reconnect...")
        time.sleep(5)
        r_binance_fundingrate = redis.Redis(connection_pool=pool_binance_fundingrate)

def run_threaded(job_func):
    job_thread = threading.Thread(target=job_func)
    job_thread.start()

if __name__ == "__main__":
    start_okx_websocket()           #okx订单簿 线程
    start_dydx_websocket()          #dydx订单簿 线程
    start_binance_websocket()       #binance订单簿 线程
    schedule.every(60).seconds.do(run_threaded, task_get_capital_rate_okx)               #okx资金费率定时任务
    schedule.every(60).seconds.do(run_threaded, task_get_orderbook_hyperliquid)          #hyper订单簿定时任务
    schedule.every(60).seconds.do(run_threaded, task_get_capital_rate_hyperliquid)       #hyper资金费率定时任务
    schedule.every(60).seconds.do(run_threaded, task_get_capital_rate_dydx)              #dydx资金费率定时任务
    schedule.every(60).seconds.do(run_threaded, task_get_capital_rate_binance)           #binance资金费率定时任务

    while True:
        schedule.run_pending()
        time.sleep(5)
        # threads = threading.enumerate()
        # # 输出线程数量
        # print(f"当前运行的线程数: {len(threads)}")